//
//  IntroScene.m
//  whattheword
//
//  Created by DRSAGITN on 7/18/14.
//  Copyright DRSAGITN 2014. All rights reserved.
//
// -----------------------------------------------------------------------

// Import the interfaces
#import "IntroScene.h"
#import "HelloWorldScene.h"

// -----------------------------------------------------------------------
#pragma mark - IntroScene
// -----------------------------------------------------------------------

@implementation IntroScene

// -----------------------------------------------------------------------
#pragma mark - Create & Destroy
// -----------------------------------------------------------------------

+ (IntroScene *)scene
{
	return [[self alloc] init];
}

// -----------------------------------------------------------------------

- (id)init
{
    // Apple recommend assigning self with supers return value
    self = [super init];
    if (!self) return(nil);
    
    // Create a colored background (Dark Grey)
    CCNodeColor *background = [CCNodeColor nodeWithColor:[CCColor colorWithRed:162/255.0 green:175/255.0 blue:14/255.0 alpha:1.0f]];
    [self addChild:background];
    
    // Hello world
    CCLabelTTF *label = [CCLabelTTF labelWithString:@"What The Words!" fontName:@"Trebuchet" fontSize:32.0f];
    label.positionType = CCPositionTypeNormalized;
    label.color = [CCColor whiteColor];
    label.position = ccp(0.5f, 0.5f); // Middle of screen
    [self addChild:label];
    
    // done
	return self;
}
- (void) onEnter{
    NSLog(@"on enter");
 
}

- (void) onEnterTransitionDidFinish{
    NSLog(@"on enter transition");
    // EACH PACKAGE HAS 50 level
    //CHECK AND DOWNLOAD NEW GAME PACKAGE IF UER NEARLY TO END PACKAGE LEVEL
    
    //get current user level
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    int currentUserLevel = [defaults integerForKey:@"user_level"];
    //get current package Id
    int currentPackageId = [defaults integerForKey:@"package_id"];// 0 : no package => set to 1 as the game has default package
    if (currentPackageId == 0) {
        currentPackageId = 1;
    }
    if ((currentPackageId*50)-currentUserLevel <=10) {
        NSLog(@"Downloading new package...");
        //send request for next package id
        CCLabelTTF *downloadingLabel = [CCLabelTTF labelWithString:@"Downloading data..." fontName:@"Chalkduster" fontSize:10.0f];
        downloadingLabel.positionType = CCPositionTypeNormalized;
        downloadingLabel.color = [CCColor whiteColor];
        downloadingLabel.position = ccp(0.5f, 0.35f);
        [self addChild:downloadingLabel];
        
        int nextPackageId = currentPackageId + 1;
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://vitago.com.vn/json?guesstheword&package=%d", nextPackageId]]];
        [request setTimeoutInterval:15];
        //NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *returnData, NSError *connectionError) {
            
            downloadingLabel.position = ccp(0.5f, 0.25f);
            if(connectionError == nil){
                //parse the returning data
                NSString *strData = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
                NSLog(strData);
                downloadingLabel.color = [CCColor greenColor];
                [downloadingLabel setString:@"New levels updated"];

            }
            else{
            // Add start button after finish
                downloadingLabel.color = [CCColor redColor];
                [downloadingLabel setString:@"Fail to update new levels"];
            }
            
            // add start button
            CCButton *helloWorldButton = [CCButton buttonWithTitle:@"[ Start ]" fontName:@"Verdana-Bold" fontSize:18.0f];
            helloWorldButton.positionType = CCPositionTypeNormalized;
            helloWorldButton.position = ccp(0.5f, 0.35f);
            [helloWorldButton setTarget:self selector:@selector(onSpinningClicked:)];
            [self addChild:helloWorldButton];
            
        }];
        
    }
    else{
        // add start button
        CCButton *helloWorldButton = [CCButton buttonWithTitle:@"[ Start ]" fontName:@"Verdana-Bold" fontSize:18.0f];
        helloWorldButton.positionType = CCPositionTypeNormalized;
        helloWorldButton.position = ccp(0.5f, 0.35f);
        [helloWorldButton setTarget:self selector:@selector(onSpinningClicked:)];
        [self addChild:helloWorldButton];

    }
    
    
}
// -----------------------------------------------------------------------
#pragma mark - Button Callbacks
// -----------------------------------------------------------------------

- (void)onSpinningClicked:(id)sender
{
    // start spinning scene with transition
    [[CCDirector sharedDirector] replaceScene:[HelloWorldScene scene]
                               withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionLeft duration:1.0f]];
}

// -----------------------------------------------------------------------
@end
